package cn.com.msui.controller.identity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.msui.common.UUIDHexGenerator;
import cn.com.msui.controller.BaseController;
import cn.com.msui.controller.JsonResult;
import cn.com.msui.domain.identity.Role;
import cn.com.msui.service.identity.RoleService;

@Controller
@RequestMapping("/identity/role")
public class RoleController extends BaseController {

	private RoleService roleService;
	private static Logger logger = Logger.getLogger(RoleController.class);

	public RoleService getRoleService() {
		return roleService;
	}

	@Autowired
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	@RequestMapping(value = "/showListRoles", method = RequestMethod.GET)
	public String showUserList() {
		return "identity/listRoles";
	}

	@RequestMapping(value = "/listRoles", method = RequestMethod.POST)
	@ResponseBody
	public List<Map<String, String>> listRoles(Role role) {
		List<Map<String, String>> showTree = new ArrayList<Map<String, String>>();
		List<Role> roleList = new ArrayList<Role>();
		try {
			roleList = roleService.getChildrenRoles(role);
			for (Role r : roleList) {
				Map<String, String> map = new HashMap<String, String>();
				if (r.getChildrenRoles() != null && r.getChildrenRoles().size() > 0)
					map.put("state", "closed");
				map.put("id", r.getId());
				map.put("text", r.getName());
				showTree.add(map);
			}
		} catch (Exception e) {
			logger.debug(e);
			e.printStackTrace();
		}
		return showTree;
	}

	@RequestMapping(value = "/saveRole")
	@ResponseBody
	public JsonResult saveRole(Role role) {
		JsonResult json = new JsonResult(false, "角色保存失败！");
		json.setObj(role);

		try {
			if (StringUtils.hasText(role.getId())) {
				roleService.modifyRole(role);
			} else {
				role.setId(UUIDHexGenerator.getInstance().generate());
				roleService.addRole(role);
			}
			json.setSuccess(true);
			json.setMsg("角色保存成功！");
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/removeRole")
	@ResponseBody
	public JsonResult removeRole(Role role) {
		JsonResult json = new JsonResult(false, "角色删除失败！");
		json.setObj(role);

		try {
			if (StringUtils.hasText(role.getId())) {
				roleService.removeRole(role);
				json.setSuccess(true);
				json.setMsg("角色删除成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}
}
